﻿using Newtonsoft.Json;
using PhysicalExamination5.Interface;
using PhysicalExamination5.Model;
using PhysicalExamination5.Model.PhysicalExamination;
using PhysicalExamination5.Model.SystemSetting;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PhysicalExamination5.Service
{
    public class SIndex : IIndex
    {
        private readonly ISqlSugarClient db;
        public SIndex(ISqlSugarClient db)
        {
            this.db = db;
        }
        /// <summary>
        ///  根据登录系统、用户Id、角色Id去查询菜单权限
        /// </summary>
        /// <param name="strDengLuXiTong"></param>
        /// <param name="strJueSeId"></param>
        /// <param name="strUserId"></param>
        /// <returns></returns>
        public string Initialize(string strDengLuXiTong, string strJueSeId, string strUserId)
        {
            int nret = 0; string strFanHuiZhi = "";
            try
			{
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:接收参数【登录系统：{strDengLuXiTong}、角色ID{strJueSeId}、用户ID{strUserId}】");

                #region 声明变量

                List<RuLeClass> listRuLeClass = new List<RuLeClass>();
                List<XT_CaiDan_Rule> listXT_CaiDan_Rule;
                RuLeClass ruLeClass;
                string strShouQuanMiaoShu = "";

                var ShouYeRule = new SqlSugarRepository<XT_CaiDan_Rule>(db).getByWhere(t => t.ShangJiRuleId == 0 && t.Type == "菜单项");
                if (ShouYeRule.Count != 0)
                {
                    ruLeClass = new RuLeClass();
                    ruLeClass.path = ShouYeRule[0].Path;
                    ruLeClass.name = ShouYeRule[0].Name;
                    ruLeClass.component = ShouYeRule[0].Component;
                    ruLeClass.meta = new Meta()
                    {
                        icon = ShouYeRule[0].Icon,
                        title = ShouYeRule[0].Title,
                        isLink = ShouYeRule[0].isLink,
                        isHide = ShouYeRule[0].isHide,
                        isFull = ShouYeRule[0].isFull,
                        isAffix = ShouYeRule[0].isAffix,
                        isKeepAlive = ShouYeRule[0].isKeepAlive
                    };
                    listRuLeClass.Add(ruLeClass);
                }

                #endregion

                #region 查询当前登录用户的菜单权限

                List<int> listCaiDanIDQuanXian = new SqlSugarRepository<qx_CaiDan>(db)
                    .getByWhere(t => t.uCode == (new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, strUserId) == 0 ? strFanHuiZhi : "") || t.JueSeID == strJueSeId)
                    .Select(t => t.CaiDanID)
                    .ToList();
                List<string> listCaiDanQuanXian = new SqlSugarRepository<XT_CaiDan_Rule>(db)
                    .getByWhere(t => listCaiDanIDQuanXian.Contains(t.RuleId))
                    .Select(t => t.Title)
                    .ToList();

                #endregion

                #region 查询授权的菜单

                var ZhuCaiDan = new SqlSugarRepository<MY_YiYuanShouQuan>(db)
                    .getByWhere(t => t.XiTongMingCheng == new MethodHelper(db).MD5Encrypt(strDengLuXiTong))
                    .Select(t => new
                    {
                        t.ZhuCaiDanMingCheng,
                        t.ZhuCaiDanShunXu,
                        t.ShouQuanJieZhiShiJian
                    })
                    .Distinct()
                    .OrderBy(t=>t.ZhuCaiDanShunXu)
                    .ToList();

                if (ZhuCaiDan.Count == 0)
                {
                    nret = 0;
                    strFanHuiZhi = "当前医院未授权请先进行授权操作！";
                    goto PROC_EXIT;
                }


                #endregion

                #region 获得医院授权截至日期

                nret = new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, ZhuCaiDan[0].ShouQuanJieZhiShiJian);
                if (nret != 0)
                {
                    nret = 1;
                    strFanHuiZhi = "加密值校验未通过!";
                    goto PROC_EXIT;
                }
                DateTime dateShouQuanJieZhiShiJian = DateTime.Parse(strFanHuiZhi);
                strFanHuiZhi = "";
                DateTime now = DateTime.Now;
                TimeSpan timeDifference = dateShouQuanJieZhiShiJian.Subtract(now);
                if (timeDifference.Days < 0)
                {
                    strShouQuanMiaoShu = $@"系统授权已到期[{dateShouQuanJieZhiShiJian.ToString("yyyy-MM-dd")}]，请联系管理员";
                }
                else
                {
                    if (timeDifference.Days < 30)
                    {
                        strShouQuanMiaoShu = $@"系统授权即将到期，剩余 {timeDifference.Days} 天";
                    }
                }

                #endregion

                #region 根据主菜单去加载子菜单

                foreach (var item in ZhuCaiDan)
                {
                    #region 获得当前主菜单下的子菜单

                    var ZiCaiDan = new SqlSugarRepository<MY_YiYuanShouQuan>(db)
                        .getByWhere(t => t.XiTongMingCheng == new MethodHelper(db).MD5Encrypt(strDengLuXiTong) && t.ZhuCaiDanMingCheng == item.ZhuCaiDanMingCheng)
                        .Select(t => new
                        {
                            t.ZiCaiDanMingCheng,
                            t.ZiCaiDanShunXu,
                        })
                        .OrderBy(t => t.ZiCaiDanShunXu)
                        .ToList();

                    List<string> listZiCaiDan = ZiCaiDan.Select(t => new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, t.ZiCaiDanMingCheng) == 0 ? strFanHuiZhi : "")
                                      .Where(t => string.IsNullOrEmpty(strFanHuiZhi) == false)
                                      .ToList();
                    strFanHuiZhi = "";

                    #endregion

                    #region 登录用户不是管理员时只返回当用户权限的菜单

                    nret = new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, strUserId);
                    if (nret != 0)
                    {
                        nret = 1;
                        strFanHuiZhi = "加密值校验未通过!";
                        goto PROC_EXIT;
                    }
                    if (strFanHuiZhi != "hcwy")
                    {
                        listZiCaiDan = listZiCaiDan.Intersect(listCaiDanQuanXian).ToList();
                    }
                    strFanHuiZhi = "";

                    #endregion

                    #region 子菜单不为时添加到集合中

                    if (listZiCaiDan.Count != 0)
                    {
                        ruLeClass = new RuLeClass();
                        nret = new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, item.ZhuCaiDanMingCheng);
                        if (nret != 0)
                        {
                            nret = 1;
                            strFanHuiZhi = "加密值校验未通过!";
                            goto PROC_EXIT;
                        }

                        listXT_CaiDan_Rule = new SqlSugarRepository<XT_CaiDan_Rule>(db).getByWhere(t => t.Title.Trim() == strFanHuiZhi.Trim());
                        if (listXT_CaiDan_Rule.Count == 0)
                        {
                            continue;
                        }
                        ruLeClass.path = listXT_CaiDan_Rule[0].Path;
                        ruLeClass.name = listXT_CaiDan_Rule[0].Name;
                        ruLeClass.redirect = listXT_CaiDan_Rule[0].Redirect;
                        ruLeClass.meta = new Meta
                        {
                            icon = listXT_CaiDan_Rule[0].Icon,
                            title = listXT_CaiDan_Rule[0].Title,
                            isLink = listXT_CaiDan_Rule[0].isLink,
                            isHide = listXT_CaiDan_Rule[0].isHide,
                            isFull = listXT_CaiDan_Rule[0].isFull,
                            isAffix = listXT_CaiDan_Rule[0].isAffix,
                            isKeepAlive = listXT_CaiDan_Rule[0].isKeepAlive,
                        };
                        List<Children> listchildren = new List<Children>();
                        foreach (string strZiCaiDan in listZiCaiDan)
                        {
                            listXT_CaiDan_Rule = new SqlSugarRepository<XT_CaiDan_Rule>(db).getByWhere(t => t.Title.Trim() == strZiCaiDan.Trim());
                            foreach (XT_CaiDan_Rule XT_CaiDan_Rule in listXT_CaiDan_Rule)
                            {
                                Children children = new Children();
                                children.path = XT_CaiDan_Rule.Path;
                                children.name = XT_CaiDan_Rule.Name;
                                children.component = XT_CaiDan_Rule.Component;
                                children.meta = new Meta
                                {
                                    icon = XT_CaiDan_Rule.Icon,
                                    title = XT_CaiDan_Rule.Title,
                                    isLink = XT_CaiDan_Rule.isLink,
                                    isHide = XT_CaiDan_Rule.isHide,
                                    isFull = XT_CaiDan_Rule.isFull,
                                    isAffix = XT_CaiDan_Rule.isAffix,
                                    isKeepAlive = XT_CaiDan_Rule.isKeepAlive,
                                };
                                listchildren.Add(children);
                            }
                        }
                        ruLeClass.children = listchildren;
                        listRuLeClass.Add(ruLeClass);
                        strFanHuiZhi = "";
                    }

                    #endregion
                }

                #endregion


            PROC_EXIT:
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = nret,
                    Message = strFanHuiZhi,
                    Data = listRuLeClass
                }) ;
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = ex.Message,
                    Data = ""
                });
            }
        }
    }
}
